package tgc.edu.exam.security;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import tgc.edu.exam.entity.SysUser;
import tgc.edu.exam.service.SysUserService;

//创建会话
@Component
public class UserUtils {
	@Autowired
	private SysUserService userService;
	
	public SysUser getUser() {
		UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String username = userDetails.getUsername();
		SysUser user = userService.findByUsername(username);
		return user;
	}
	
	public Boolean hasRole(String roleCode) {
		UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		List<String> roleCodes=new ArrayList<>();
		for (GrantedAuthority authority : userDetails.getAuthorities()) {
			roleCodes.add(authority.getAuthority());
		}
		return roleCodes.contains(roleCode);
	}
	
	public String getName() {
		if(hasRole("ROLE_DIY")) {
			return "开发者";
		}
		return getUser().getName();
	}
}
